<template>
  <div class="anni">
    <!-- ----------左侧------- -->
    <div class="conner">
      <div
        id="mapContainer"
        class="conner-gaode"
        style="width: 100%; height: 100%"
      ></div>

      <i @click="drawer = true" class="el-icon-s-tools shezhi"></i>
    </div>
    <!-- ----------右侧------- -->
    <el-drawer
      title="地图设置"
      :visible.sync="drawer"
      @close="closeHandel"
      :wrapperClosable="false"
      direction="rtl"
    >
      <div class="search-container but-box">
        <div class="search-box">
          <!-- 搜索查询 -->

          <div class="each-line">
            <div class="each-name">路线导航</div>
            <el-tabs v-model="tabsName" type="border-card">
              <el-tab-pane name="1" label="经纬度查询">
                <!-- 起点输入框 -->
                <div class="input-group">
                  <div class="input-with-icon">
                    <div class="location-icon start">起</div>
                    <el-autocomplete
                      v-model.trim="startNamelon"
                      clearable
                      :fetch-suggestions="querySearch"
                      placeholder="请输入起点经度"
                    ></el-autocomplete>
                    <el-autocomplete
                      v-model.trim="startNamelat"
                      clearable
                      :fetch-suggestions="querySearch"
                      placeholder="请输入起点纬度"
                    ></el-autocomplete>
                  </div>
                </div>
                <!-- 终点输入框 -->
                <div class="input-group">
                  <div class="input-with-icon">
                    <div class="location-icon end">终</div>
                    <el-autocomplete
                      v-model.trim="endNamelon"
                      clearable
                      :fetch-suggestions="querySearch"
                      placeholder="请输入终点经度"
                    ></el-autocomplete>
                    <el-autocomplete
                      v-model.trim="endNamelat"
                      clearable
                      :fetch-suggestions="querySearch"
                      placeholder="请输入终点纬度"
                    ></el-autocomplete>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane name="2" label="名称查询">
                <!-- 起点输入框 -->
                <div class="input-group">
                  <div class="input-with-icon">
                    <div class="location-icon start">起</div>
                    <el-autocomplete
                      v-model="textStartName"
                      clearable
                      :fetch-suggestions="querySearch"
                      placeholder="请输入起点名"
                    ></el-autocomplete>
                  </div>
                </div>
                <!-- 终点输入框 -->
                <div class="input-group">
                  <div class="input-with-icon">
                    <div class="location-icon end">终</div>
                    <el-autocomplete
                      v-model="textEndName"
                      clearable
                      :fetch-suggestions="querySearch"
                      placeholder="请输入终点名"
                    ></el-autocomplete>
                  </div>
                </div>
              </el-tab-pane>
              <el-button type="primary" class="search-btn" @click="goView"
                >查询路线</el-button
              >
            </el-tabs>
          </div>
          <!-- <div class="each-line">
            <div class="each-name">设置默认中心点</div>
            <div class="acquiesce-point">
              <el-input
                class="inp"
                v-model.trim="acqlonVal"
                placeholder="默认点经度"
              ></el-input>
              <el-input
                class="inp"
                v-model.trim="acqlatVal"
                placeholder="默认点纬度"
              ></el-input>
              <el-button type="primary" size="mini" @click="acquiesceChange"
                >确认</el-button
              >
            </div>
          </div> -->
          <div class="each-line">
            <div class="each-name">切换3D/2D地图</div>
            <div class="acquiesce-point">
              <el-radio-group @change="stereChange" v-model="isStereogram">
                <el-radio :label="1">2D地图</el-radio>
                <el-radio :label="2">3D地图</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div class="each-line">
            <div class="each-name">绘制多边形</div>
            <div class="acquiesce-point">
              <el-button @click="startDrawPolygon" type="primary">
                绘制多边形
              </el-button>
            </div>
          </div>
          <div class="each-line">
            <div class="each-name">设置起始点路径</div>
            <div class="acquiesce-point">
              <el-button
                type="primary"
                class="search-btn"
                @click="isEditChange"
                >{{ isEdit ? "结束编辑" : "开始编辑" }}</el-button
              >
            </div>
          </div>
          <!-- 按钮组 -->
          <div class="each-line button-group">
            <div class="each-name">其它操作</div>
            <div>
              <el-button
                type="info"
                plain
                class="reset-btn"
                @click="butyuandian"
                >回到原点</el-button
              >
              <!-- <el-button
                plain
                type="success"
                class="reset-btn"
                @click="intoChange"
                >添加地图标记</el-button
              > -->
              <div class="home">
                <div id="mapContainer"></div>
                <el-button
                  plain
                  type="success"
                  class="reset-btn"
                  @click="importFromFileSystem"
                >
                  导入坐标数据
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    <div id="panel"></div>
    <!-- -----------右侧结束----------- -->
    <!-- 弹窗 -->
    <el-dialog
      title="批量导入"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <div class="coordinate" v-for="(item, index) in coordList" :key="index">
          <span class="coor-name">经度{{ index + 1 }}：</span
          ><el-input
            v-model.trim="item.lonValue"
            placeholder="请输入经度坐标"
          ></el-input>
          <span class="coor-name">纬度{{ index + 1 }}：</span
          ><el-input
            v-model.trim="item.latValue"
            placeholder="请输入纬度坐标"
          ></el-input>
          <i
            class="el-icon-circle-plus-outline icon"
            @click="addCoorHandle"
          ></i>
          <i
            v-show="index > 0"
            class="el-icon-delete delete-icon"
            @click="delCoorHandle(index)"
          ></i>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from "element-ui";
export default {
  data() {
    return {
      isEdit: false,
      kaishi: false,
      newLat: "",
      newlng: "",
      isStereogram: 2, //立体图像1--2D 2--3D
      acqlonVal: "", //设置默认点经度
      acqlatVal: "", //设置默认点纬度
      autoComplete: null,
      drawer: false,
      map: null,
      // marker: null,
      tabsName: "1",
      dialogVisible: false,
      startNamelon: "",
      startNamelat: "",
      textStartName: "",
      endNamelon: "",
      endNamelat: "",
      textEndName: "",
      markers: [], // 用于存储所有标记点
      coordList: [{ lonValue: "", latValue: "" }],
      // intVal: [121.010754, 28.059426], //浙江省温州市乐清市纬十二路148号 [104.07518, 30.68594] 成都坐标点
      // intVal: [121.00935482210022, 28.06858994547522],
      // intVal: [104.07518, 30.68594],
      // intVal: [104.07518, 30.68594, 210],
      intVal: [121.010948315, 28.068447985, 14.9540005],
      positions: [],
      polygons: [],
      quanbd: [], //绘制多边形时被圈中的标记点
      mouseTool: null,
    };
  },
  created() {},
  mounted() {
    this.initMap();
    // 初始化时，为坐标中心点添加内容
  },
  methods: {
    // 批量导入坐标
    async importFromFileSystem() {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".txt";

      input.onchange = async (event) => {
        const file = event.target.files[0];
        if (file) {
          const text = await file.text();
          const coordinates = [];

          const lines = text.split("\n");
          lines.forEach((line) => {
            const match = line.match(
              /\((\d+\.\d+),\s*(\d+\.\d+),\s*(\d+\.\d+)\)/
            );
            if (match) {
              const lat = parseFloat(match[1]);
              const lng = parseFloat(match[2]);
              const z = parseFloat(match[3]); // 将Z轴高度调整为建筑物顶部的高度 100写死的高度
              const adjustedHeight = z + 100;

              coordinates.push({
                position: [lat, lng],
                height: adjustedHeight,
                timestamp: parseFloat(match[4]), // 添加时间戳，确保唯一性
                // index: index, // 保存原始顺序
              });
            }
          });
          // lines.forEach((line) => {
          //   const match = line.match(
          //     /\((\d+\.\d+),\s*(\d+\.\d+),\s*(\d+\.\d+)\)/
          //   );
          //   if (match) {
          //     coordinates.push({
          //       position: [parseFloat(match[1]), parseFloat(match[2])],
          //       height: parseFloat(match[3]),
          //     });
          //   }
          // });

          this.positions = coordinates;
          if (coordinates.length > 0) {
            this.intVal = coordinates[0].position;
            window.map.setCenter(coordinates[0].position);
          }

          // 添加标记点
          // this.addMarkers();
          // 分批添加标记点
          await this.addMarkersWithAnimation(coordinates);

          console.log(`成功导入 ${coordinates.length} 个坐标点`);
        }
      };

      input.click();
      this.drawer = false;
    },
    // 新增分批渲染方法
    async addMarkersWithAnimation(coordinates) {
      const batchSize = 50; // 每批添加的标记点数量
      const delay = 100; // 每批之间的延迟时间（毫秒）
      const total = coordinates.length;
      let processed = 0;
      const markers = [];

      // 清除现有标记点
      if (this.markers) {
        this.markers.forEach((marker) => marker.setMap(null));
      }
      this.markers = [];
      // 创建进度条组件
      const loading = Message({
        message: "正在加载标记点...",
        duration: 0,
        type: "warning",
        showClose: true,
      });
      try {
        // 分批处理坐标点
        for (let i = 0; i < coordinates.length; i += batchSize) {
          const batch = coordinates.slice(i, i + batchSize);

          // 创建当前批次的标记点
          const batchMarkers = batch.map((item, index) => {
            const marker = new AMap.Marker({
              position: item.position,
              title: `点位 ${i + index + 1}`,
              animation: "AMAP_ANIMATION_DROP", // 添加掉落动画
              label: {
                content: `高程: ${item.height.toFixed(2)}m`,
                direction: "top",
              },
            });

            // 根据高程设置不同的图标样式
            const icon = this.getMarkerIcon(item.height);
            if (icon) {
              marker.setIcon(icon);
            }

            return marker;
          });

          // 将当前批次的标记点添加到地图
          window.map.add(batchMarkers); // 使用数组批量添加标记点
          this.markers.push(...batchMarkers);
          // // 添加聚合功能
          // if (!this.markerCluster) {
          //   this.markerCluster = new AMap.MarkerClusterer(
          //     window.map,
          //     this.markers,
          //     {
          //       gridSize: 80,
          //       minClusterSize: 2,
          //     }
          //   );
          // } else {
          //   this.markerCluster.setMarkers(this.markers);
          // }
          // 更新进度
          processed += batchSize;
          loading.message = `已加载 ${processed}/${total} 个标记点 (${Math.round(
            (processed / total) * 100
          )}%)`;
          // 等待指定延迟时间
          await new Promise((resolve) => setTimeout(resolve, delay));
        }

        // 完成后显示成功提示
        loading.close();
        Message.success(`成功加载 ${total} 个标记点`);
      } catch (error) {
        loading.close();
        Message.error("加载标记点时发生错误");
      }
    },
    // 根据高程返回不同的图标样式
    getMarkerIcon(height) {
      let color;
      if (height < 50) {
        color = "#3498db"; // 蓝色
      } else if (height < 200) {
        color = "#2ecc71"; // 绿色
      } else {
        color = "#e74c3c"; // 红色
      }

      return new AMap.Icon({
        type: "image", // 图标类型，现阶段只支持 image 类型
        // 可以使用内置图标或自定义图片
        size: [19, 31],
        // imageSize: new AMap.Size(25, 34),
        image: "//webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
        anchor: "center", // 图片相对 position 的锚点，默认为 bottom-center
      });
    },
    // 初始化
    initMap() {
      window.map = new AMap.Map("mapContainer", {
        rotateEnable: true, //是否开启地图旋转交互 鼠标右键 + 鼠标画圈移动 或 键盘Ctrl + 鼠标画圈移动
        pitchEnable: true, // 是否开启地图倾斜交互 鼠标右键 + 鼠标上下移动或键盘Ctrl + 鼠标上下移动
        center: this.intVal, //初始地图中心经纬度
        zoom: 9.5, //初始化地图层级 17
        terrain: true, // 开启地形图
        viewMode: this.isStereogram == 1 ? "2D" : "3D", // 根据当前模式设置初始视图
        pitch: this.isStereogram == 1 ? 0 : 76, // 根据当前模式设置俯仰角 地图俯仰角度，有效范围 0 度- 83 度
        // rotation: 80, //初始地图顺时针旋转的角度
        // 隐藏默认楼块
        features: ["bg", "road", "point"],
        layers: [
          // 卫星
          new AMap.TileLayer.Satellite(),
          // 路网
          new AMap.TileLayer.RoadNet(),
          // 楼块图层
          new AMap.Buildings({
            zooms: [16, 18], //图层缩放等级范围，默认 [2, 20]
            zIndex: 90,
            heightFactor: 3, //2倍于默认高度，3D下有效
            wallColor: "rgba(88, 88, 88,1)",
            roofColor: "rgba(42, 42, 42,1)",
          }),
        ],
        resizeEnable: true,
        //----
        // touchZoomCenter: 1,
        // touchZoom: true,
        // preventScroll: true,
        // scrollWheel: true,
      });

      this.addControl();
      this.addAcquiesce();
      // this.addMarkers();
    },
    //添加地图控件
    addControl() {
      try {
        AMap.plugin(["AMap.MarkerClusterer"], () => {
          AMap.plugin(
            [
              "AMap.ControlBar",
              "AMap.ToolBar",
              "AMap.Driving",
              "AMap.AutoComplete",
              "AMap.PlaceSearch",
              "AMap.Scale",
              "AMap.MouseTool",
            ],
            () => {
              // 添加指南针控件
              const controlBar = new AMap.ControlBar({
                position: {
                  right: "10px",
                  top: "10px",
                },
              });
              window.map.addControl(controlBar);
              const toolBar = new AMap.ToolBar({
                //地图缩放插件
                position: {
                  right: "40px",
                  top: "110px",
                },
              });
              window.map.addControl(toolBar);
              this.autoComplete = new AMap.AutoComplete({
                city: "全国",
              });
              const scale = new AMap.Scale({
                visible: true,
              });
              window.map.addControl(scale);
              // 绘制多边形
              this.mouseTool = new AMap.MouseTool(window.map);
              // ------------添加点击事件
              this.driving = new AMap.Driving({
                map: window.map,
                panel: "panel", // 路线详细信息面板，可选
                policy: AMap.DrivingPolicy.LEAST_TIME, // 最快捷模式
              });
              // 添加地图点击事件
              window.map.on("click", (e) => {
                this.handleMapClick(e);
              });
            }
          );
        });
      } catch (error) {
        console.error("初始化地图控件时出错:", error);
        this.$message.error("初始化地图控件失败");
      }
    },
    // ---------------------------------------------------------------------
    // 获取多边形内的标记点
    getMarkersInPolygon(polygon) {
      if (!this.markers || !polygon) return [];
      this.quanbd = [];
      try {
        const path = polygon.getPath();
        if (!path || !Array.isArray(path)) {
          console.warn("无效的多边形路径");
          return [];
        } 
        // 过滤并收集标记点信息
        const markersInfo = this.markers.filter((marker) => {
          try {
            const position = marker.getPosition();
            if (!position) return false;

            const isInside = AMap.GeometryUtil.isPointInRing(
              [position.getLng(), position.getLat()],
              path.map((p) => [p.getLng(), p.getLat()])
            );

            if (isInside) {
              // 获取标记点的详细信息
              const obj = {
                position: {
                  longitude: position.getLng(),
                  latitude: position.getLat(),
                },
                height: marker.getExtData()?.height || 0, // 获取高度信息(如果存在)
                title: marker.getTitle(),
                label: marker.getLabel()?.content, // 获取标签内容
                extData: marker.getExtData(), // 获取额外数据
              };
              this.quanbd.push(obj);
              return obj;
            }
            return false;
          } catch (err) {
            console.warn("处理单个标记点时出错:", err);
            return false;
          }
        });
        return markersInfo;
      } catch (err) {
        console.error("获取多边形内标记点时出错:", err);
        return [];
      }
    },

    // 开始绘制多边形
    startDrawPolygon() {
      if (!this.mouseTool) {
        console.error("MouseTool 未初始化");
        return;
      }
      this.drawer = false;
      // -----------------------------------------------------------
      // 监听绘制完成事件

      // -----------------------------------------------------------
      // 关闭其他绘制模式
      this.mouseTool.close();

      // 显示提示信息
      this.$message({
        message: "请点击地图绘制多边形，双击完成绘制",
        type: "info",
        duration: 3000,
      });
      try {
        // 移除之前的事件监听器
        this.mouseTool.off("draw");
        // 添加绘制完成事件监听
        this.mouseTool.on("draw", (event) => {
          try {
            const { obj: polygon } = event;
            if (!polygon) {
              console.warn("未能获取到多边形对象");
              return;
            }
            // 保存多边形
            if (!this.polygons) this.polygons = [];
            this.polygons.push(polygon);
            // 获取多边形内的标记点
            const markersInPolygon = this.getMarkersInPolygon(polygon);
            // 显示多边形信息
            const path = polygon.getPath();
            if (!path) {
              console.warn("未能获取到多边形路径");
              return;
            }
            const area = this.calculateArea(path);

            // 创建信息窗体显示多边形信息和内部标记点数量
            const infoContent = `
              <div class="polygon-info">
                <h3>多边形信息</h3>
                <p>面积：${area.toFixed(2)} 平方米</p>
                <p>包含标记点：${
                  Array.isArray(markersInPolygon) ? markersInPolygon.length : 0
                } 个</p>
              </div>
            `;

            // 创建并打开信息窗体
            const bounds = polygon.getBounds();
            if (bounds) {
              new AMap.InfoWindow({
                content: infoContent,
                position: bounds.getCenter(),
                offset: new AMap.Pixel(0, -10),
              }).open(window.map);

              // 添加多边形点击事件
              polygon.on("click", () => {
                try {
                  const currentPath = polygon.getPath();
                  if (!currentPath) return;
                  const currentArea = this.calculateArea(currentPath);
                  const currentMarkers = this.getMarkersInPolygon(polygon);

                  new AMap.InfoWindow({
                    content: `
                    <div class="polygon-info">
                      <p>面积：${currentArea.toFixed(2)} 平方米</p>
                      <p>包含标记点：${
                        Array.isArray(currentMarkers)
                          ? currentMarkers.length
                          : 0
                      } 个</p>
                    </div>
                  `,
                    position: polygon.getBounds()?.getCenter(),
                  }).open(window.map);
                } catch (err) {
                  console.error("处理多边形点击事件时出错:", err);
                }
              });
            }
          } catch (err) {
            console.error("处理绘制完成事件时出错:", err);
            this.$message.error("绘制多边形时出现错误");
          } finally {
            // 绘制完成后关闭绘制工具
            this.mouseTool.close();
          }
        });
        // 开启多边形绘制模式
        this.mouseTool.polygon({
          fillColor: "#00CD00",
          strokeColor: "#00CD00",
          strokeWeight: "6",
          // strokeOpacity: 1,
          // strokeWeight: 2,
          // strokeStyle: "solid",
          // fillOpacity: 0.4,
          // 是否可编辑
          // editable: true,
          // 是否可拖动
          // draggable: true,
        });
      } catch (err) {
        console.error("启动多边形绘制时出错:", err);
        this.$message.error("无法启动多边形绘制工具");
      }
    },
    // 计算面积
    calculateArea(path) {
      if (!path || !path.length) return 0;

      try {
        // 转换坐标格式
        const coordinates = path.map((p) => [p.getLng(), p.getLat()]);
        return AMap.GeometryUtil.ringArea(coordinates);
      } catch (error) {
        console.error("计算面积错误:", error);
        return 0;
      }
    },
    // 绘制完成回调
    drawComplete(e) {
      if (!e || !e.obj) {
        console.error("绘制对象为空");
        return;
      }

      const polygon = e.obj;

      try {
        // 获取多边形的路径坐标
        const path = polygon.getPath();
        if (!path || !path.length) {
          console.error("路径为空");
          return;
        }

        // 将坐标转换为正确的格式
        const coordinates = path
          .map((point) => {
            // 确保点位是 LngLat 对象
            if (point instanceof AMap?.LngLat) {
              return [point.getLng(), point.getLat()];
            } else if (Array.isArray(point)) {
              return point;
            } else if (point.lng && point.lat) {
              return [point.lng, point.lat];
            }
            console.error("无效的坐标点", point);
            return null;
          })
          .filter((point) => point !== null);

        // 计算面积
        const area = this.calculateArea(path);

        // 添加信息窗体
        const center = polygon.getBounds().getCenter();
        const infoWindow = new AMap.InfoWindow({
          content: `<div>面积：${area.toFixed(2)} 平方米</div>`,
          position: center,
          offset: new AMap.Pixel(0, -10),
        });

        // 添加点击事件
        polygon.on("click", () => {
          infoWindow.open(this.map);
        });

        // 保存多边形对象
        if (!this.polygons) this.polygons = [];
        this.polygons.push(polygon);
      } catch (error) {
        console.error("处理多边形时出错：", error);
      }

      // 绘制完成后关闭绘制工具
      this.mouseTool.close();
    },
    // ---------------------------------------------------------------------
    // ------------------------------------
    isEditChange() {
      this.isEdit = !this.isEdit;
      if (this.isEdit) this.drawer = false;
    },
    handleMapClick(e) {
      if (!e || !e.lnglat) return;
      const { lat, lng } = e.lnglat;
      this.newlng = lng;
      this.newLat = lat;
      if (this.kaishi) {
        // 第二次点击终点
        this.endNamelon = this.newlng.toString();
        this.endNamelat = this.newLat.toString();
        this.kaishi = false;
        this.drawer = true;
        return;
      }
      if (this.isEdit) {
        // 第一次点击  开始规划起点
        this.kaishi = true; //起点已开始规划中
        this.startNamelon = this.newlng.toString();
        this.startNamelat = this.newLat.toString();
      }

      // const lnglat = e.lnglat;

      // // 如果没有起点，设置起点
      // if (!this.startMarker) {
      //   this.startMarker = new AMap.Marker({
      //     position: lnglat,
      //     map: this.map,
      //     icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png",
      //     title: "起点",
      //   });
      //   return;
      // }

      // // 如果有起点没有终点，设置终点并规划路线
      // if (!this.endMarker) {
      //   this.endMarker = new AMap.Marker({
      //     position: lnglat,
      //     map: this.map,
      //     icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-spot.png",
      //     title: "终点",
      //   });

      //   // 规划路线
      //   this.planRoute();
      // } else {
      //   // 如果起点和终点都存在，清除现有路线重新开始
      //   this.clearRoute();
      // }
    },

    // 规划路线
    planRoute() {
      if (!this.startMarker || !this.endMarker) return;

      this.driving.search(
        this.startMarker.getPosition(), // 起点
        this.endMarker.getPosition(), // 终点
        {
          waypoints: [], // 途经点，可选
          showTraffic: true, // 显示实时路况，可选
        },
        (status, result) => {
          if (status === "complete") {
            console.log("规划成功", result);
            // 可以在这里处理规划成功后的操作
          } else {
            console.error("规划失败", result);
          }
        }
      );
    },

    // 清除路线和标记点
    clearRoute() {
      if (this.driving) this.driving.clear();
      if (this.startMarker) {
        this.startMarker.setMap(null);
        this.startMarker = null;
      }
      if (this.endMarker) {
        this.endMarker.setMap(null);
        this.endMarker = null;
      }
    },

    // 使用已知坐标规划路线
    planRouteByCoordinates(startPos, endPos) {
      // 清除现有路线
      this.clearRoute();

      // 添加起点标记
      this.startMarker = new AMap.Marker({
        position: startPos,
        map: this.map,
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png",
        title: "起点",
      });

      // 添加终点标记
      this.endMarker = new AMap.Marker({
        position: endPos,
        map: this.map,
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-spot.png",
        title: "终点",
      });

      // 规划路线
      this.planRoute();
    },
    // ------------------------------------
    // 创建中心点
    addAcquiesce() {
      // 创建一个 icon
      let endIcon = new AMap.Icon({
        // size: new AMap.Size(25, 34),
        image: "//webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
        // imageSize: new AMap.Size(135, 40),
        // imageOffset: new AMap.Pixel(-95, -3),
      });

      // 将 icon 传入 marker
      let endMarker = new AMap.Marker({
        // position: new AMap.LngLat(121.010948315, 28.068447985, 14.9540005),
        position: this.intVal,
        icon: endIcon,
        zIndex: 99,
        anchor: "bottom-center",
        offset: new AMap.Pixel(0, 0),
      });
      endMarker.setLabel({
        offset: new AMap.Pixel(20, 20), //设置文本标注偏移量
        content: "<div class='zhongxin'>中心坐标</div>", //设置文本标注内容
        direction: "top",
      });
      window.map.add([endMarker]);
    },
    // 添加多个标记点
    addMarkers() {
      // 添加多个标记点
      this.positions.forEach((item) => {
        const marker = new AMap.LabelMarker({
          position: item.position,
          title: item.title,
          animation: "AMAP_ANIMATION_DROP", // 点标记的动画效果
          icon: new AMap.Icon({
            // 图标类型，现阶段只支持 image 类型
            type: "image",
            // 可选颜色：red, blue, green, yellow, purple, etc.
            image: "//webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
            size: [19, 31],
            // imageSize: new AMap.Size(19, 31),
            // 图片相对 position 的锚点，默认为 bottom-center
            anchor: "center",
          }),
        });
        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
          content: `<div>
                    <h3>${item.title}</h3>
                    <p>${item.content}</p>
                </div>`,
          offset: new AMap.Pixel(0, -30),
        });
        // 绑定点击事件
        marker.on("click", () => {
          infoWindow.open(window.map, marker.getPosition());
        });
        // 将标记添加到地图
        window.map.add(marker);
        // 保存标记点引用
        this.markers.push(marker);
      });
      //-----------------------------------------------------------
      // const geolocation = new AMap.Geolocation({
      //     enableHighAccuracy: true, // 是否使用高精度定位，默认为false
      //     timeout: 10000, // 超过10秒后停止定位，默认为无穷大
      //     buttonPosition: 'RB', // 定位按钮的位置
      //     buttonOffset: new AMap.Pixel(10, 10) // 定位按钮的偏移量
      // })
      // map.addControl(geolocation)
      // geolocation.getCurrentPosition()
    },
    // 清除所有标记点
    clearMarkers() {
      if (this.markers.length) {
        window.map.remove(this.markers);
        this.markers = [];
      }
    },
    // 更新标记点
    updateMarkers(newPositions) {
      this.clearMarkers();
      this.positions = newPositions;
      this.addMarkers();
    },
    // 回到原点
    butyuandian() {
      //  let bounds= window.map.getBounds()
      //  window.map.setLimitBounds(bounds)
      //通过 new AMap.Bounds(southWest:LngLat, northEast:LngLat) 或者 map.getBounds() 获得地图Bounds信息
      var mybounds = new AMap.Bounds(this.intVal, this.intVal);
      window.map.setBounds(mybounds);
      this.drawer = false;
    },
    //设置默认中心点
    acquiesceChange() {
      this.intVal = [this.acqlonVal, this.acqlatVal];
      this.initMap();
      this.drawer = false;
    },
    // -------------------------右侧---------------------
    intoChange() {
      this.dialogVisible = true;
    },
    confirmHandle() {
      this.positions = [];
      for (let i = 0; i < this.coordList.length; i++) {
        const item = this.coordList[i];
        this.positions.push({
          position: [item.lonValue, item.latValue],
          title: `标记${i + 1}`,
          content: "这是标记的详细信息",
        });
      }
      this.updateMarkers(this.positions);
      this.dialogVisible = false;
    },
    addCoorHandle() {
      this.coordList.push({ lonValue: "", latValue: "" });
    },
    delCoorHandle(i) {
      this.coordList.splice(i, 1);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    goView() {
      if (
        (this.tabsName === "1" &&
          ((!this.startNamelon && !this.startNamelat) ||
            (!this.endNamelon && !this.endNamelat))) ||
        (this.tabsName === "2" && (!this.textStartName || !this.textEndName))
      ) {
        this.$message.warning("请先选择起点和终点");
        return;
      }
      if (!this.driving) {
        AMap.plugin(["AMap.Driving"], () => {
          this.driving = new AMap.Driving({
            map: window.map,
            panel: "panel",
            ferry: 1, // 是否可以使用轮渡
            policy: AMap.DrivingPolicy.LEAST_TIME,
          });
          this.searchRoute();
        });
      } else {
        this.searchRoute();
      }
      this.drawer = false;
    },
    searchRoute() {
      const lnglat =
        this.tabsName === "1"
          ? [
              // new AMap.LngLat(104.07518, 30.68594),
              new AMap.LngLat(this.startNamelon, this.startNamelat),
              // new AMap.LngLat(104.077363, 30.685237),
              new AMap.LngLat(this.endNamelon, this.endNamelat),
            ]
          : [];
      const lname = [
        [
          { keyword: this.textStartName, city: "全国" },
          { keyword: this.textEndName, city: "全国" },
        ],
      ];
      const sear = this.tabsName === "1" ? lnglat : lname;
      this.driving.search(...sear, function (status, result) {
        if (status === "complete") {
          console.log("规划路线成功", result);
        } else {
          this.$message.error("路线规划失败");
          console.error("规划路线失败", result);
        }
      });
    },
    searchClose() {
      this.driving.clear();
    },
    // 查询建议地点
    querySearch(queryString, callback) {
      if (queryString.length === 0) {
        callback([]);
        return;
      }

      this.autoComplete.search(queryString, (status, result) => {
        if (status === "complete" && result.tips) {
          const tips = result.tips.map((tip) => ({
            value: tip.name,
            address: tip.district + tip.address,
            location: tip.location,
          }));
          callback(tips);
        } else {
          callback([]);
        }
      });
    },
    closeHandel(e) {},
    // 2/3D地图切换 代码后续优化
    stereChange(e) {
      window.map.destroy(); // 销毁当前地图实例
      if (e == 1) {
        window.map = new AMap.Map("mapContainer", {
          rotateEnable: true, //是否开启地图旋转交互 鼠标右键 + 鼠标画圈移动 或 键盘Ctrl + 鼠标画圈移动
          pitchEnable: true, // 是否开启地图倾斜交互 鼠标右键 + 鼠标上下移动或键盘Ctrl + 鼠标上下移动
          center: this.intVal, //初始地图中心经纬度
          zoom: 13.8, //初始化地图层级 17
          terrain: true, // 开启地形图
          pitch: 0,
          // rotation: 80, //初始地图顺时针旋转的角度
          // 隐藏默认楼块
          features: ["bg", "road", "point"],
          layers: [
            // 卫星
            new AMap.TileLayer.Satellite(),
            // 路网
            new AMap.TileLayer.RoadNet(),
            // 楼块图层
            new AMap.Buildings({
              zooms: [16, 18], //图层缩放等级范围，默认 [2, 20]
              zIndex: 10,
              heightFactor: 3, //2倍于默认高度，3D下有效
              wallColor: "rgba(42, 42, 42,0.9)",
              roofColor: "rgba(42, 42, 42,0.8)",
            }),
          ],
          resizeEnable: true,
          //----
          // touchZoomCenter: 1,
          // touchZoom: true,
          // preventScroll: true,
          // scrollWheel: true,
        });
      } else {
        window.map = new AMap.Map("mapContainer", {
          rotateEnable: true,
          pitchEnable: true,
          center: this.intVal, //初始地图中心经纬度
          zoom: 13.8, //初始化地图层级 17
          terrain: true, // 开启地形图
          viewMode: "3D",
          pitch: 76,
          // 隐藏默认楼块
          features: ["bg", "road", "point"],
          layers: [
            // 卫星
            new AMap.TileLayer.Satellite(),
            // 路网
            new AMap.TileLayer.RoadNet(),
            // 楼块图层
            new AMap.Buildings({
              zooms: [16, 18], //图层缩放等级范围，默认 [2, 20]
              zIndex: 10,
              heightFactor: 3, //2倍于默认高度，3D下有效
              wallColor: "rgba(42, 42, 42,0.9)",
              roofColor: "rgba(42, 42, 42,0.8)",
            }),
          ],
          resizeEnable: true,
        });
      }
      this.addControl();
      this.addAcquiesce();
      this.addMarkers();
      this.drawer = false;
    },
  },

  beforeDestroy() {
    try {
      // 清理多边形
      if (this.polygons) {
        this.polygons.forEach((polygon) => {
          if (polygon) {
            polygon.setMap(null);
          }
        });
      }

      // 清理标记点
      if (this.markers) {
        this.markers.forEach((marker) => {
          if (marker) {
            marker.setMap(null);
          }
        });
      }

      // 清理绘制工具
      if (this.mouseTool) {
        this.mouseTool.close();
      }

      // 销毁地图实例
      if (window.map) {
        window.map.destroy();
      }
    } catch (err) {
      console.error("清理资源时出错:", err);
    }
    // 组件销毁前清除标记点
    this.clearMarkers();
  },
};
</script>
<style scoped lang="less">
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}
.anni {
  width: 100%;
  height: 100%;
  display: flex;
  .conner {
    flex: 0 0 100%;
    position: relative;
    .shezhi {
      position: absolute;
      // padding-top: 20px;
      // padding-bottom: 20px;
      right: 20px;
      bottom: 20px;
      z-index: 9999;
      font-size: 50px;
      color: #ffffff;
    }
  }
  .but-box {
    flex: 1;
  }
}
.coordinate {
  display: flex;
  align-items: center;
  padding: 8px 0;
  .coor-name {
    display: inline-block;
    width: 60px;
    margin-left: 26px;
  }
}
.el-input {
  width: 180px;
}
.icon {
  font-size: 26px;
  margin: 0 8px;
  color: rgb(10, 158, 243);
}
.delete-icon,
.icon {
  cursor: pointer;
}
// --------------------查询路线------------------
#panel {
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 100px;
  right: 78px;
  width: 280px;
}
#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}
.amap-call {
  display: none;
}
#panel .amap-lib-walking {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  overflow: hidden;
}
.search-box {
  .el-autocomplete {
    margin-right: 10px;
  }
}
// ---------------------右侧抽屉---------------------------
// 美化搜索结果下拉框
:deep(.el-autocomplete-suggestion) {
  li {
    line-height: 1.5;
    padding: 7px 10px;
    .value {
      font-size: 14px;
      font-weight: bold;
    }
    .address {
      font-size: 12px;
      color: #999;
      margin-top: 3px;
    }
  }
}
.search-container {
  padding: 20px;
}

.search-box {
  .input-group {
    margin-bottom: 12px;
    .input-with-icon {
      display: flex;
      align-items: center;
      gap: 8px;

      .location-icon {
        min-width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        color: white;

        &.start {
          background-color: #67c23a;
        }

        &.end {
          background-color: #f56c6c;
        }
      }

      .el-input {
        flex: 1;
      }
    }
  }

  .button-group {
    gap: 8px;
    margin-top: 16px;

    .search-btn,
    .reset-btn {
      margin-top: 4px;
      margin-bottom: 4px;
      flex: 1;
    }
  }
}

// 输入框样式优化
:deep(.el-input__inner) {
  border-radius: 4px;
  height: 36px;

  &:focus {
    border-color: #409eff;
  }
}

// 响应式适配
@media screen and (max-width: 768px) {
  .search-box {
    width: calc(100vw - 40px);
  }
}
/deep/.el-drawer__header {
  font-size: 18px;
  color: #000;
  font-weight: 600;
}
.each-line {
  margin-bottom: 10px;
  .each-name {
    font-size: 16px;
    padding: 8px 0;
    font-weight: 600;
  }
}
.acquiesce-point {
  display: flex;
  .inp {
    margin: 0 4px;
  }
}
/deep/.amap-marker-label {
  top: -46px !important;
  border: 1px solid transparent;
  border-radius: 10px;
  z-index: 999;
}
/deep/.zhongxin {
  font-size: 18px;
  color: rgb(53, 127, 224);
  font-weight: 600;
}
</style>
